package com.cn.redis.utils;


import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component("com.cn.redis.utils.IDGenerator")
public final class c {
    private String P;
    private volatile long Q;
    private volatile long R;
    private volatile int step;
    private static c S;
    @Resource(
            name = "com.cn.redis.utils.Bootstrap"
    )
    private a T;

    public c() {
    }

    @PostConstruct
    public void init() {
        S = this;
        S.T = this.T;
    }

    public void init(String seqName, int step) {
        if (StringUtils.isEmpty(seqName)) {
            throw new IllegalArgumentException("缺少seqName");
        } else {
            this.P = seqName;
            this.step = step;
        }
    }

    public void J() {
        S.T.start(this.P);
    }

    public synchronized long next() {
        if (this.Q >= this.R) {
            this.J();
            this.R = this.K();
            this.Q = this.R - (long)this.step;
        }

        ++this.Q;
        return this.Q;
    }

    public synchronized List<Object> f(int size) {
        List<Object> currentList = new ArrayList();
        if (this.Q + (long)size >= this.R) {
            this.J();
            this.R = this.K();
            this.Q = this.R - (long)this.step;
        }

        for(int i = 0; i < size; ++i) {
            ++this.Q;
            currentList.add(this.Q);
        }

        return currentList;
    }

    private long K() {
        return S.T.a(this.P, this.step);
    }

    public String L() {
        return this.P;
    }

    public void f(String seqName) {
        this.P = seqName;
    }
}
